from flask import request,session,render_template,json
from application.group import group
from db_util.models import db,Group,GroupMember,User,Schedule,GroupTask,Events,Colleague
from sqlalchemy import and_
import random,datetime

#######################################
#         界面跳转：小组模块
#######################################
#跳转到添加小组界面
@group.route("/group/to_add_group")
def to_add_group():
    return render_template("group/add_group.html")

#######################################
#         定义接口：小组模块
#######################################
#获取用户小组列表
@group.route("/group/user_group_list",methods=['GET'])
def userGroupList():
    user_id = session['user_id'];
    #获取用户加入的小组列表
    my_group_list = getMyGroupList();
    #根据user_id获取到用户的列表信息（GroupMember）
    group_member_list = db.session.query(GroupMember).filter(GroupMember.user_id == user_id).all()
    user_group_list = []
    if (group_member_list):
        #如果有列表信息，则根据列表中的小组id，查询出小组的相关信息
        for group_item in group_member_list:
            user_group_item_list = db.session.query(Group).filter(Group.id == group_item.group_id).all()
            if (user_group_item_list):
                group = user_group_item_list[0]
                #根据小组信息中的leader查询用户信息
                user_list = db.session.query(User).filter(User.id == group.group_leader).all()
                if(user_list):
                    user = user_list[0]
                    group.group_leader_name = user.nickname;
                user_group_list.append(group)
    db.session.close();
    return render_template("user/group_index.html",
                           user_group_list=user_group_list,
                           my_group_list = my_group_list);

#获取组长为当前用户的小组信息
def getMyGroupList():
    group_list = db.session.execute('select * from group_list where group_leader = :user_id ',{'user_id': session['user_id']})
    return group_list;

#小组新增
@group.route("/group/group_add",methods=['GET','POST'])
def group_add():
    data = request.get_data("data")
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)

    group = Group();
    group.group_name = data['group_name'];
    group.group_mark = data['group_mark'];
    group.group_task = data['group_task'];
    group.group_key = data['group_key'];
    group.group_leader = session['user_id'];

    db.session.add(group);
    db.session.commit();
    db.session.close();
    return("SUCCESS")
    # 暂时不考虑小组重复的问题
    # group_list = db.session.query(Group).filter(Group.group_name == group.group_name).all()
    # if(group_list):
    #     return("小组名已存在")
    # else:
    #     db.session.add(group)
    #     db.session.commit()
    #     return("新增小组成功")

#小组解散
@group.route("/group/group_delete",methods=['GET','POST'])
def group_delete():
    data = request.get_data("data")
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)
    groupId = data['group_id'];
    group_member_list = db.session.query(GroupMember).filter(GroupMember.group_id == groupId).all();
    for item in group_member_list:
        leader_id = session['user_id'];
        colleague = db.session.query(Colleague).filter(
            and_(Colleague.user_id == item.user_id, Colleague.colleague_id == leader_id)).first();
        colleague.permission = 0;
        db.session.merge(colleague);
    db.session.execute('delete from group_list where id =:id',
                       {'id': int(groupId)});
    db.session.commit();
    db.session.close();
    return ("小组解散成功")
    # if(group_list):
    #     #     db.session.remove(group_list[0])
    #     #     return("小组解散成功")
    #     # else:
    #     #     return("小组解散失败")

#小组邀请同事
@group.route("/group/group_add_colleague",methods=['GET','POST'])
def group_add_colleague():
    data = request.get_data("data")
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)

    nickname = data['nickname'];
    group_id = data['group_id'];
    user = db.session.query(User).filter(User.nickname == nickname).first();
    if(user):
        group_member = GroupMember();
        group_member.group_id = group_id;
        group_member.user_id = user.id;
        db.session.add(group_member);
        db.session.commit();
        group = db.session.query(Group).filter(Group.id == group_id).first();
        leader_id = group.group_leader;
        colleague = db.session.query(Colleague).filter(and_(Colleague.user_id == user.id,Colleague.colleague_id == leader_id)).first();
        colleague.permission =1;
        db.session.merge(colleague);
        db.session.commit();
        db.session.close();
        return ("邀请用户成功")
    else:
        db.session.close();
        return ("用户信息错误")


#小组删除同事
@group.route("/group/group_delete_colleague",methods=['GET','POST'])
def group_delete_colleague():
    groupMember = GroupMember()
    groupMember.user_id = request.form.get("user_id")
    groupMember.group_id = request.form.get("group_id")

    query = db.session.query(GroupMember).filter(groupMember.user_id == GroupMember.user_id)
    groupMember_list = query.filter(GroupMember.group_id == groupMember.group_id).all()
    if (groupMember_list):
        db.session.remove(groupMember)
        db.session.commit()
        group = db.session.query(Group).filter(Group.id == groupMember.group_id).first();
        leader_id = group.group_leader;
        colleague = db.session.query(Colleague).filter(
            and_(Colleague.user_id == groupMember.user_id, Colleague.colleague_id == leader_id)).first();
        colleague.permission = 0;
        db.session.merge(colleague);
        db.session.commit();
        db.session.close();
        return ("用户删除成功")
    else:
        db.session.close();
        return ("该用户不存在")


#小组成员权限设置
@group.route("/group/group_colleague_permission",methods=['GET','POST'])
def group_colleague_permission():
    return

#修改小组信息
@group.route("/group/group_info_update",methods=['GET','POST'])
def group_info_update():
    data = request.get_data("data")
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)

    group = Group();
    group.id = data['group_id'];
    group.group_name = data['group_name'];
    group.group_mark = data['group_mark'];
    group.group_task = data['group_task'];
    group.group_key = data['group_key'];
    group.group_leader = session['user_id'];
    db.session.merge(group);
    db.session.commit();
    db.session.close();
    return("SUCCESS")

#加入小组
@group.route("/group/group_join",methods=['GET','POST'])
def group_join():
    data = request.get_data("data")
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)

    group_name = data['group_name'];
    group_key = data['group_key'];

    #first查询出来的就是对象，不是列表
    group = db.session.query(Group).filter(and_(Group.group_name == group_name,Group.group_key == group_key)).first()
    if(group):
        groupMember = GroupMember();
        groupMember.group_id = group.id
        groupMember.user_id = session["user_id"]
        db.session.add(groupMember)
        db.session.commit()
        db.session.close();
        return("加入小组成功！")
    else:
        db.session.close();
        return("密钥错误！")


#退出小组
@group.route("/group/group_quit",methods=['GET','POST'])
def group_quit():
    data = request.get_data("data")
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)

    group_id = data['group_id'];

    group_id = group_id
    user_id = session["user_id"]
    groupMember = db.session.query(GroupMember).filter(and_(GroupMember.user_id == user_id,GroupMember.group_id == group_id)).first();
    if(groupMember):
        group = db.session.query(Group).filter(Group.id == group_id).first();
        leader_id = group.group_leader;
        colleague = db.session.query(Colleague).filter(
            and_(Colleague.user_id == user_id, Colleague.colleague_id == leader_id)).first();
        colleague.permission = 0;
        db.session.merge(colleague);
        db.session.commit();
        db.session.delete(groupMember)
        db.session.commit()
        db.session.close();
        return ("退出小组成功！")
    else:
        db.session.close();
        return("退出小组失败！")



#小组成员列表
@group.route("/group/group_member_list",methods=['GET','POST'])
def group_member_list():
    groupMember = GroupMember()
    groupMember.group_id = request.form.get("group_id")
    groupMember_list = db.session.query(groupMember.group_id == GroupMember.group_id).all()
    if(groupMember_list):
        user_info_list = []
        for groupMember_item in groupMember_list:
            user_id = groupMember_item.user_id
            user_list = db.session.query(User.user_id == user_id).all()
            if(user_list):
                user = user_list[0]
                user_info_list.append(user)
        print("group_member_list 获取小组成员列表成功")
        db.session.close();
        return (user_info_list)
    else:
        db.session.close();
        return("group_member_list 获取小组成员列表失败")

#成员任务分配
@group.route("/group/group_job_schedule",methods=['GET','POST'])
def group_job_schedule():
    schedule = Schedule()
    schedule.title = request.form.get('title')
    schedule.value = request.form.get('value')
    schedule.repeat = request.form.get('repeat')
    schedule.alerm = request.form.get('alerm')
    schedule.repeat_cycle = request.form.get('repeat_cycle')
    schedule.user_id = session["user_id"]
    db.session.add(schedule)
    db.session.commit()
    db.session.close();
    return ("group_job_schedule 成员任务分配成功")

#小组任务
@group.route("/group/group_tasking",methods=['GET','POST'])
def group_tasking():
    group = Group()
    group.group_id = request.form.get("group_id")
    group_task = request.form.get("group_task")
    group_list = db.session.query(Group.id == group.id).all()
    if(group_list):
        group = group_list[0]
        group.group_task = group_task
        db.session.add(group)
        db.session.commit()
        db.session.close();
        return("新建小组任务成功")
    else:
        db.session.close();
        return("新建小组任务失败")

#小组任务修改
# @group.route("/group/group_tasking_update",methods=['GET','POST'])
# def group_tasking_update():
#     group = Group()
#     group.group_id = request.form.get("group_id")
#     group_task = request.form.get("group_task")
#     group_list = db.session.query(Group.id == group.id).all()
#     if(group_list):
#         group = group_list[0]
#         group.group_task = group_task
#         db.session.merge(group)
#         db.session.commit()
#         return("修改小组任务成功")
#     else:
#         return("修改小组任务失败")

#小组任务删除
@group.route("/group/group_tasking_delete",methods=['GET','POST'])
def group_tasking_delete():
    group = Group()
    group.group_id = request.form.get("group_id")
    group_list = db.session.query(Group.id == group.id).all()
    if(group_list):
        group = group_list[0]
        group.group_task = ""
        db.session.merge(group)
        db.session.commit()
        db.session.close();
        return("删除小组任务成功")
    else:
        db.session.close();
        return("删除小组任务失败")

# #会议时间推荐
# @group.route("/group/group_metting_recommend",methods=['GET','POST'])
# def group_metting_recommend():
#     return

#小组详情界面
@group.route("/group/group_detail",methods=['GET','POST'])
def group_detail():
    group_id = request.args.get("group_id");
    #获取组长Id
    group = db.session.query(Group).filter(Group.id == group_id).first();
    user = db.session.query(User).filter(User.id == group.group_leader).first();
    if(user):
        group.group_leader_name = user.nickname;

    # 获取小组成员列表
    group_member_list = db.session.query(GroupMember).filter(GroupMember.group_id == group_id).all();
    user_list = [];
    if(group_member_list):
        for item in group_member_list:
            user = db.session.query(User).filter(User.id == item.user_id).first();
            if(user):
                user_list.append(user);

    #获取小组代办列表
    group_task_list = db.session.query(GroupTask).filter(GroupTask.group_id == group_id).all();
    db.session.close();
    return render_template("user/group_detail.html",user_list = user_list,
                           group_task_list=group_task_list,currentGroupId = group_id,
                           groupInfo=group);

#新增小组代办
@group.route("/group/group_task_add",methods=['GET','POST'])
def group_task_add():
    data = request.get_data("data");
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)

    group_task = GroupTask();
    group_task.group_id = data['group_id'];
    group_task.task = data['group_task'];
    group_task.finished = 0;
    db.session.add(group_task);
    db.session.commit();
    db.session.close();
    return("新增成功！");

#完成小组待办
@group.route("/group/group_task_finish",methods=['GET','POST'])
def group_task_finish():
    data = request.get_data("data");
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)

    group_task_id = data['groupTaskId'];
    groupTask = db.session.query(GroupTask).filter(GroupTask.id == group_task_id).first();
    if(groupTask):
        # db.session.execute('delete from group_task where id=:id', {'id': group_task_id})
        groupTask.finished = 1;
        db.session.merge(groupTask);
        db.session.commit();
        db.session.close();
        return("小组待办完成！");
    else:
        db.session.close();
        return("小组待办完成出现错误！");

#完成小组待办
@group.route("/group/group_task_delete",methods=['GET','POST'])
def group_task_dekete():
    data = request.get_data("data");
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)

    group_task_id = data['groupTaskId'];
    groupTask = db.session.query(GroupTask).filter(GroupTask.id == group_task_id).first();
    if(groupTask):
        db.session.execute('delete from group_task where id=:id', {'id': group_task_id})
        db.session.commit();
        db.session.close();
        return("小组待办删除成功！");
    else:
        db.session.close();
        return("小组待办删除出现错误！");

#添加会议到小组日程
@group.route("/group/group_meet_add",methods=['GET','POST'])
def group_meet_add():
    meettime = session['random'];
    data = request.get_data("data");
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)
    group_id = data['group_id'];
    if(meettime!=""):
        # nowTime = datetime.datetime.now().strftime('%Y-%m-%d')
        # print(meettime.split())
        meettime_ary = meettime.split("-");
        day1_ary = meettime_ary[2].split();
        day1 = day1_ary[0];
        start_date = meettime_ary[0]+"-"+meettime_ary[1]+"-"+day1+" "+day1_ary[1]+":00";
        end_year = day1_ary[3];
        day2_ary = meettime_ary[4].split();
        day2 = day2_ary[0];
        end_date = day1_ary[3]+"-"+meettime_ary[3]+"-"+day2+" "+day2_ary[1]+":00";
        # times = meettime.split();
        # starttime = times[0];
        # endtime = times[2];
        # start_time = str(nowTime)+" "+starttime;
        # end_time = str(nowTime)+" "+endtime;
        group_member_list = db.session.query(GroupMember).filter(GroupMember.group_id == group_id).all();
        if (group_member_list):
            for item in group_member_list:
                user = db.session.query(User).filter(User.id == item.user_id).first();
                if (user):
                    events = Events();
                    events.start_date = start_date;
                    events.end_date = end_date;
                    events.text = "会议";
                    events.level = 2;
                    events.user_id = user.id;
                    db.session.add(events);
                    db.session.commit();
            db.session.close();
            return("会议日程添加成功！");
    else:
        db.session.close();
        return("会议日程添加出错！");

#会议时间获取
@group.route("/group/group_meet_time_get",methods=['GET','POST'])
def group_meet_time_get():
    data = request.get_data("data");
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)
    start_time = datetime;
    start_time = data['start_time'];
    start_time_split = start_time.split();
    start_date = start_time_split[0];
    start_time_hms = start_time_split[1].split(":");
    start_time_hour = start_time_hms[0];

    end_time = datetime;
    end_time = data['end_time'];
    end_time_split = end_time.split();
    end_date = end_time_split[0];
    end_time_hms = end_time_split[1].split(":");
    end_time_hour = end_time_hms[0];
    # start_time = int(data['start_time']); #会议开始时间
    # end_time = int(data['end_time']);       #会议结束时间
    long_time = int(data['long_time']);  #会议时长
    random_end_time = int(end_time_hour) - long_time;
    random_start = random.randint(int(start_time_hour), random_end_time)
    random_end = random_start + long_time;
    random_time =str(start_date)+" "+str(random_start) + ":00 至 " + str(start_date)+" "+str(random_end) + ":00";
    session['random'] = random_time;
    db.session.close();
    return random_time;

#删除小组成员
@group.route("/group/group_member_delete",methods=['GET','POST'])
def group_member_delete():
    data = request.get_data("data");
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data);
    userId = data['user_id'];
    groupId = data['group_id'];
    groupMember_list = db.session.query(GroupMember).filter(GroupMember.group_id == groupId).all()
    if (groupMember_list):
        group = db.session.query(Group).filter(Group.id == groupId).first();
        leader_id = group.group_leader;
        colleague = db.session.query(Colleague).filter(
            and_(Colleague.user_id == userId, Colleague.colleague_id == leader_id)).first();
        colleague.permission = 0;
        db.session.merge(colleague);
        db.session.commit();
        db.session.execute('delete from group_member where group_id=:groupId and user_id =:userId',
                           {'groupId': groupId, 'userId': userId});
        db.session.commit();
        db.session.close();
    db.session.close();
    return ("删除小组成员成功！");